//
//  MCOrderSearchViewController.swift
//  StoreManage
//
//  Created by MC on 2017/12/21.
//  Copyright © 2017年 MC. All rights reserved.
//

import UIKit

class MCOrderSearchViewController: MCViewController {
    
    public var status : Int = 0  // 0全部，2待发货，3待收货，4已完成（核销页面传0）
    
    public var activityLogId = 0  // 活动分销记录Id 可选
    
    public var writeOffStatus = 0 // 1未核销；2已核销；3快递送（核销统计传参）
    
    private var pageNumber = 1
    private var searchType = 2   // 1商品；2订单；3联系人；4联系人电话
    private var searchWord = ""
    
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        
        navigationController?.navigationBar.addSubview(titleTextField)
    }
    
    override func viewDidAppear(_ animated: Bool) {
        super.viewDidAppear(animated)
        titleTextField.becomeFirstResponder()
    }
    
    
    override func viewWillDisappear(_ animated: Bool) {
        super.viewWillDisappear(animated)
        titleTextField.resignFirstResponder()
        titleTextField.removeFromSuperview()
    }
    

    

    
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        baseSetting()
        
        initUI()
        
        managerClosure()
    }
    
    // MARK: - System Delegate
    
    // MARK: - Custom Delegate
    
    // MARK: - Closure
    func managerClosure() {
    }
    // MARK: - Action
    @objc override func leftItemClicked() {
        let alter = UIAlertController.init(title: "请选择搜索条件", message: nil, preferredStyle: UIAlertControllerStyle.actionSheet)
        let cancle = UIAlertAction.init(title: "取消", style: UIAlertActionStyle.cancel) { (a) in
            
        }
        
        let one = UIAlertAction.init(title: "商品", style: UIAlertActionStyle.default) { (a) in
            self.searchType = 1
            self.leftButton.setTitle(" 商品", for:.normal)
        }
        
        let two = UIAlertAction.init(title: "姓名", style: UIAlertActionStyle.default) { (a) in
            self.searchType = 3
            self.leftButton.setTitle(" 姓名", for:.normal)
        }
        
        let three = UIAlertAction.init(title: "订单编号", style: UIAlertActionStyle.default) { (a) in
            self.searchType = 2
            self.leftButton.setTitle(" 订单编号", for:.normal)
        }
        
        let four = UIAlertAction.init(title: "手机号", style: UIAlertActionStyle.default) { (a) in
            self.searchType = 4
            self.leftButton.setTitle(" 手机号", for:.normal)
        }
        
        
        alter.addAction(cancle)
        alter.addAction(one)
        alter.addAction(two)
        alter.addAction(three)
        alter.addAction(four)
        
        self.present(alter, animated: true, completion: nil)
    }
    
    @objc func rightItemClicked() {
        self.navigationController?.popViewController(animated: true)
    }
    
    // MARK: - Network
    func sendNetworking() {
        let para = [
            "storeId" : MCUserinfo_getStoreId(),
            "status"  : status,
            "pageNum" : pageNumber,
            "activityLogId" : activityLogId,
            "searchType" : searchType,
            "searchWord" : searchWord
            ] as [String : Any]
        
        MCNetwork_post(url: JAVA_getStoreOrderList, para: para as [String : AnyObject], vc: self,hudSuperView: self.view,isHiddenTabbar: true, success: { (response) in
            
            
            self.tableView.mj_header.endRefreshing()
            self.tableView.mj_footer.endRefreshing()
            
            if self.pageNumber == 1 {
                self.dataArrayM.removeAllObjects()
            }
            
            
            let dataDict = response["data"] as! [String : AnyObject]
            let array = dataDict["list"] as! NSArray
            
            if array.count + self.dataArrayM.count == 0 {
                self.tableView.showBgImage()
            } else {
                self.tableView.hideBgImage()
                
                for dict in array {
                    let fatherModel = MCOrderListFatherModel()
                    fatherModel.setValuesForKeys(dict as! [String : Any])
                    self.dataArrayM.add(fatherModel)
                }
            }
            
            self.tableView.reloadData()
            
        }, dislike: { (response) in }) { (error) in }
        
    }
    
    // MARK: - Method
    func baseSetting() {
        self.view.backgroundColor = UIColor.white
        

        
        
        let bar = UIBarButtonItem.init(customView: leftButton)
        
        self.navigationItem.leftBarButtonItem = bar
        
        navigationItem.rightBarButtonItem = MCSetBarButtonItem_text("取消", target: self, selector: #selector(rightItemClicked))

        
        self.tableView.mj_header = MCRefreshHeader.init(refreshingBlock: {
            self.pageNumber = 1
            self.sendNetworking()
        })
        
        self.tableView.mj_footer = MCRefreshFooter.init(refreshingBlock: {
            self.pageNumber += 1
            self.sendNetworking()
        })
    }
    
    func initUI() {
        view.addSubview(tableView)
        tableView.snp.remakeConstraints { (make) ->Void in
            make.edges.equalTo(view).inset(UIEdgeInsetsMake(0, 0, CGFloat(MCSafeAreaBottomHeight), 0))
        }
    }
    
    // MARK: - Setter & Getter
    lazy private var tableView: MCTableView = {
        let tableView = MCTableView.init(frame: CGRect.zero, style: UITableViewStyle.grouped)
        tableView.delegate = self
        tableView.dataSource = self
        tableView.keyboardDismissMode = UIScrollViewKeyboardDismissMode.onDrag
        return tableView
    }()
    
    lazy var dataArrayM: NSMutableArray = {
        let arrayM = NSMutableArray()
        return arrayM
    }()
    
    lazy var leftButton: UIButton = {
        let butotn = UIButton.init(type: UIButtonType.custom)
        butotn.frame = CGRect.init(x: 0, y: 0, width: 60, height: 40)
        butotn.setImage(#imageLiteral(resourceName: "Reuse_triangle_black_bottom"), for: .normal)
        butotn.setTitleColor(UIColor.MCWords, for: .normal)
        butotn.titleLabel?.font = MCFont(14)
        butotn.setTitle(" 订单编号", for: .normal)
        butotn.addTarget(self, action: #selector(leftItemClicked), for: .touchUpInside)
        return butotn
    }()
    
    lazy var titleTextField: MCTextFiled = {
        let tf = MCTextFiled()
        tf.backgroundColor = UIColor.MCGray_light
        tf.font = MCFont(14)
        tf.placeholder = "商品/姓名/手机号/订单编号"
        tf.layer.cornerRadius = 16
        tf.layer.masksToBounds = true
        tf.returnKeyType = UIReturnKeyType.search
        tf.delegate = self
        tf.frame = CGRect.init(x: 95, y: 6, width: MCScreenWidth - 155, height: 32)

        
        let view = UIView()
        view.frame = CGRect.init(x: 0, y: 0, width: 10, height: 10)
        tf.leftView = view
        tf.leftViewMode = .always
        
        return tf
    }()
}

extension MCOrderSearchViewController : UITextFieldDelegate {
    func textFieldShouldReturn(_ textField: UITextField) -> Bool {
        
        self.searchWord = textField.text ?? ""
        self.titleTextField.resignFirstResponder()
        sendNetworking()
        return true
    }
}

extension MCOrderSearchViewController : UITableViewDelegate,UITableViewDataSource {
    
    func numberOfSections(in tableView: UITableView) -> Int {
        return self.dataArrayM.count
    }
    
    func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
        return 55
    }
    
    func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
        let view = MCOrderListSectionHeaderView()
        view.model = self.dataArrayM[section] as! MCOrderListFatherModel
        return view
    }
    
    func tableView(_ tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat {
        return 45
    }
    
    func tableView(_ tableView: UITableView, viewForFooterInSection section: Int) -> UIView? {
        let view = MCOrderListSectionFooterView()
        view.model = self.dataArrayM[section] as! MCOrderListFatherModel
        return view
    }
    
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        
        let model = self.dataArrayM[section] as! MCOrderListFatherModel
        
        return model.listBaOrderDetailVo.count
    }
    
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        return 100
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        
        let model = self.dataArrayM[indexPath.section] as! MCOrderListFatherModel
        
        let cell = MCOrderListCell.init(style: UITableViewCellStyle.value1, reuseIdentifier: "cell")
        
        cell.selectionStyle = UITableViewCellSelectionStyle.none
        
        cell.model = model.listBaOrderDetailVo[indexPath.row] as! MCOrderListModel
        
        return cell
    }
    
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        
        let model = self.dataArrayM[indexPath.section] as! MCOrderListFatherModel
        
        switch model.status {
        case 2:
            let vc = MCOrderDetailWaitSendViewController()
            vc.orderSn = model.orderSn
            MCPushToViewController(current: self, target: vc, isHiddenBottomBarWhenBack: true)
            break
        case 3:
            let vc = MCOrderDetailWaitPickUpViewController()
            vc.orderSn = model.orderSn
            MCPushToViewController(current: self, target: vc, isHiddenBottomBarWhenBack: true)
        case 4:
            let vc = MCOrderDetailCompleteViewController()
            vc.orderSn = model.orderSn
            MCPushToViewController(current: self, target: vc, isHiddenBottomBarWhenBack: true)
            
        case 6:
            let vc = MCOrderDetailSuccessfulDealViewController()
            vc.orderSn = model.orderSn
            MCPushToViewController(current: self, target: vc, isHiddenBottomBarWhenBack: true)
        default:
            break
        }
    }
}

